package com.hephesto.service.impl;

import com.hephesto.infra.security.crypto.CryptographerFactory;
import com.hephesto.infra.security.crypto.ICryptographer;
import com.hephesto.infra.security.crypto.helper.CryptographerHelper;
import com.hephesto.infra.security.crypto.model.CryptographerAlgoritmSupported;
import com.hephesto.model.authentication.exception.AuthenticationFaliedException;
import com.hephesto.model.authentication.helper.AuthenticationHelper;
import com.hephesto.model.bank.Account;
import com.hephesto.model.bank.User;
import com.hephesto.service.IAuthenticationService;

public class AuthenticationServiceImpl implements IAuthenticationService {
	
	private ICryptographer cryptographer;
	
	public void setCryptographer(ICryptographer cryptographer) {
		this.cryptographer = cryptographer;
	}

	@Override
	public boolean authentication(Account account, String password) throws AuthenticationFaliedException {
		
		/*
		 * encrypt pswd obtained 
		 */
		CryptographerFactory factory = CryptographerFactory.getInstance();
		ICryptographer cryptographer = factory.createCryptographer( CryptographerAlgoritmSupported.SHA_256 );
		
		byte[] pswdEncryptedBytes = cryptographer.encrypt( password.getBytes() );
		String pswdEncrypted = CryptographerHelper.byteArrayTobase64( pswdEncryptedBytes ); 
		
		/*
		 * compare pswd encrypt with user data persisted
		 */
		User user = new User(); // TODO obter user do dao depois
		
		if ( user.getPassword().equals( pswdEncrypted ) ) {
			throw new AuthenticationFaliedException( "Authentication falied. Login and/or Password are invalids." );
		}
		
		return false;
	}

	@Override
	public boolean authenticationToken(Account account, String token)
			throws AuthenticationFaliedException {
		
		// TODO obter tokens do banco
		
		java.util.Set<String> tokens = 
			AuthenticationHelper.convertTokensStructure( account.getTokenMachine().getTokens() );
		
		if ( tokens.contains( token ) ) {
			throw new AuthenticationFaliedException("Authentication falied. Token invalid");
		}
		
		return false;
	}
	
}